package com.tzbank.wisdom.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.tzbank.entity.FrequentContacts;
import com.tzbank.entity.Theme;
import com.tzbank.utils.CodeUtil;
import com.tzbank.utils.HttpUtil;
import com.tzbank.utils.ResultUtil;
import com.tzbank.wisdom.entity.BaseBean;
import com.tzbank.wisdom.entity.dto.BusinessFieldsDTO;
import com.tzbank.wisdom.service.AIService;
import com.tzbank.wisdom.service.BusinessService;
import com.tzbank.wisdom.utils.BusinessCodeUtil;
import com.tzbank.wisdom.utils.BusinessConstant;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Slf4j
@Service(value = "aiService")
public class AIServiceImpl implements AIService {

	@Autowired
    RestTemplate restTemplate;
	
	@Autowired
    private BusinessService businessService;
    
    /**
     * 调用AI接口服务
     */
    public Map<String,Object> aiApply(Map<String,Object> model, String url) {
    	HttpEntity<String> entity = HttpUtil.createHttpEntity(model);		//获取spring web的消息实体
 		Map<String,Object> reslut =  restTemplate.postForObject(url, entity, Map.class);		//获取的结果
 		log.info("AI调用结果返回" + reslut);
 		
 		//判断是否是语音
 		if(url.indexOf(BusinessConstant.INTO_VOICE) >= 0) {
 			//获取请求公共信息
 	 		BaseBean baseBean = new BaseBean();
 	 		try {
 				BeanUtils.copyProperties(baseBean, model);
 			} catch (Exception e) {
 				log.info("BeanUtils.copyProperties转换",e);
 			}
 	 		
 			Map<String,Object> result = formatVoiceData(reslut);		//数据模型转换
 			
 			String code = (String) result.get("code");				//语意识别编码
 			if(!BusinessConstant.AI_VOVICE_SUCCESS_CODE.equals(code)) {
 				return result;
 			}
 	    	JSONObject beanObj = JSONObject.fromObject(result.get("bean"));
 	    	
 	    	/* 转账-获取常用联系人数据 start */
 	    	FrequentContacts frequentContacts = new FrequentContacts();
 	    	
 	    	Object userId = model.get("userId");
 	    	if(userId != null) {
 	    		frequentContacts.setUserId(String.valueOf(userId));			//存在userId 进行赋值
 	    	}
 	    	
 	    	frequentContacts.setName(beanObj.getString("payee"));
 	    	Map<String, Object> resultMap = this.businessService.transferSelectContacts(frequentContacts);
 	    	if(resultMap.get("code").equals(CodeUtil.CODE_200.getCode()) && !StringUtils.isEmpty(String.valueOf(resultMap.get("data")))) {
 	    		JSONObject contactsJSON = JSONObject.fromObject(resultMap.get("data"));
 	    		frequentContacts = (FrequentContacts) JSONObject.toBean(contactsJSON, FrequentContacts.class);
 	    		beanObj.put("payeeAccount", frequentContacts.getCardNumber());
 	    		beanObj.put("payee", frequentContacts.getName());
 	    		beanObj.put("payeeBank", frequentContacts.getBankType());
 	    	}
 	    	/* 转账-获取常用联系人数据 end */
 	    	 
 	    	beanObj.putAll(JSONObject.fromObject(baseBean));		//将设备基础信息放入到bean中
 	    	return businessService.getPageflow(beanObj);
 		}else {
 			return reslut;
 		}
 		
    }
    
    /**
 	 * 语意解析数据模型转换
 	 * @param voice
 	 * @return
 	 */
 	public Map<String,Object> formatVoiceData(Map<String,Object> resultMap) {
 		JSONObject result =  JSONObject.fromObject(resultMap);			//字符转对象，  需要添加try 
 		log.info("AI返回成功：" + result);
 		String code = result.getString("code");			//语意识别编码
 		if(!BusinessConstant.AI_VOVICE_SUCCESS_CODE.equals(code)) {
 			return resultMap;
 		}else {
 			try {
 				//语音识别成功，但是data为null
 				if("null".equals(result.getString("data"))) {
 					return ResultUtil.resultMap(BusinessCodeUtil.CODE_20001.getName(), BusinessCodeUtil.CODE_20001.getCode(), null);
 				}
 				JSONObject data = JSONObject.fromObject(result.getString("data"));		//数据
 				
 				/*				
 	 			String intentType = data.getString("intentType");		//业务类型
 	 			JSONArray semanticArr = JSONArray.fromObject(data.get("semantic"));		//语意集合
 	 			JSONArray slotsArr = JSONArray.fromObject(JSONObject.fromObject(semanticArr.get(0)).get("slots"));		//语意字段集合
 				 */
 				
 				//语音解析判断
 				if(!data.has("intent")) {
 					return ResultUtil.resultMap(BusinessCodeUtil.CODE_20001.getName(), BusinessCodeUtil.CODE_20001.getCode(), null);
 				}
 				String intent = data.getString("intent");		
 				JSONObject _intentType = JSONObject.fromObject(intent);		//数据	
 				
 				//语义解析判断
 				if(!_intentType.has("semantic")) {
 					return ResultUtil.resultMap(BusinessCodeUtil.CODE_20004.getName(), BusinessCodeUtil.CODE_20004.getCode(), null);
 				}
 				JSONArray semanticArr = JSONArray.fromObject(_intentType.get("semantic"));		//语意集合			
 				JSONArray slotsArr = JSONArray.fromObject(JSONObject.fromObject(semanticArr.get(0)).get("slots"));		//语意字段集合							
 				String intentType = _intentType.getString("intentType");//业务类型 			
 	 		
 				//主题转换和数据模型映射
 	 			Map<String,Object> beanModel = new HashMap<String,Object>();
 	 			Theme themeMap = businessService.selectThemeByIflytek(intentType);
 	 			
 	 			if(themeMap == null) {
 	 				return ResultUtil.resultMap(BusinessCodeUtil.CODE_20002.getName(), BusinessCodeUtil.CODE_20002.getCode(), null);
 	 			}
 	 			
 	 			beanModel.put("themeId", themeMap.getThemeId());
 	 			beanModel.put("code", BusinessConstant.AI_VOVICE_SUCCESS_CODE);
 	 			
 	 			//根据业务id获得业务元素和科大字段映射集合
 	 			String businessId = (String) themeMap.getBusinessId();
 	 			List<BusinessFieldsDTO> listBusiness =  businessService.selectBusinessIflytekListByid(businessId);
 	 			
 	 			JSONObject bean = new JSONObject();
 	 			bean.element("themeId", themeMap.getThemeId());
 	 			//遍历业务元素集合
 	 			for(BusinessFieldsDTO businessEle : listBusiness) {
 	 				String businessFieldsName = businessEle.getBusinessFieldsName();		//业务元素
 	 				bean.element(businessFieldsName, "");			//放入元素置空
 	 				//判断是否存在业务元素和科大字段的映射关系
 	 				String iflytekFieldsName = businessEle.getIflytekFieldsName();
 	 				if(iflytekFieldsName != null) {
 	 					//存在映射关系后，判断科大返回的语意字段集合能否匹配
 	 					for(Object slots : slotsArr) {
 	 						JSONObject slotsJson =  (JSONObject) slots;
 	 						String fileName = slotsJson.getString("name");
 	 					//现AIUI有2种钱的字段: money 和	money_2     一致将转成  money
										if(fileName.equalsIgnoreCase("money_2")) {
											fileName="money";
										}
 	 						//匹配字段
 	 						if(fileName.equals(iflytekFieldsName)) {
 	 							bean.element(businessFieldsName, slotsJson.getString("normValue"));			//赋值
 	 							break;		//跳出本次for循环
 	 						}
 	 					}
 	 				}
 	 			}
 	 			beanModel.put("bean", bean);
 	 			return beanModel;
			} catch (Exception e) {
				log.info("语义AI返回的文字进行语义解析", e);
				return ResultUtil.resultMap(BusinessCodeUtil.CODE_20003.getName(), BusinessCodeUtil.CODE_20003.getCode(), null);
			}
 		}
 	}
}
